<template>
  <div class="RollRoom">
    <div class="hedar-box">
      <div class="title">{{$store.state.currentRoolRoom.rollName}}</div>
      <div class="hedar-img-box">
        <div><img :src="$store.state.currentRoolRoom.userImage" ></div>
        <p>{{$store.state.currentRoolRoom.userName}}</p>
      </div>
      <div class="text-box">
        <div>
          <p>开奖时间：<span>{{$store.state.currentRoolRoom.lotteryTime || '人满即开'}}</span></p>
          <p>说明：{{$store.state.currentRoolRoom.remark}}</p>
        </div>
        <div v-if="$store.state.currentRoolRoom.status == 0 || (width <= 100 && width != 0)" @click="participateIn()">{{allowParticipate || isLogin ? '立即参与' : (width <= 100 && width != 0) ? '开奖中……' : '您已参与'}}</div>
        <div v-else class="activ">已结束</div>
      </div>
    </div>
    <div class="Jackpot modal-cent">
      <div class="title">奖池</div>
      <div class="amount-box">
        <p>总数:<span>{{$store.state.currentRoolRoom.skinNum}}</span>件</p>
        <p>总价值:<span>{{$store.state.currentRoolRoom.priceNum}}</span></p>
      </div>
      <!-- 进度条在0-100显示进度条 -->
      <div class="settlement-box" v-if="width <= 100 && width != 0">
        <p>努力结算中:  {{width > 100 ? 100 : width}}%</p>
        <div><p :style="'width:'+(100 - (width > 100 ? 100 : width))+'%'"> </p></div>
      </div>
      <div v-else>
        <rolljackpot ref="rollJackpots"></rolljackpot>
      </div>
    </div>
    <div class="gamePlayer modal-cent">
      <div class="title">参与玩家</div>
      <div class="amount-box">
        <p>共计:<span>{{ userTotal || 0 }}</span>人</p>
      </div>
      <div class="gameHedar">
        <ul>
          <li v-for="(item ,index) in list" :key="index"><div><img :src="item.userImage" ></div><p>{{item.userName}}</p></li>
        </ul>
        <v-pagination :total="userTotal" :display="display" :current-page='userPageNum' @pagechange="pagechange"></v-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import Bus from "../../config/bus.js";
  import Stomp from "stompjs"
  import rolljackpot from '../components/rolljackpot.vue'
  import pagination from '../components/pagination.vue'
import { wsUrl } from '../common/config.js';
  export default {
    components:{
      rolljackpot,
      'v-pagination': pagination,
    },
   data () {
      return {
        mqtt: null,
        userTotal: 1,     // 记录总条数
        userPageNum: 1,
        display: 10,   // 每页显示条数
        width: 0,   //进度条
        list: [],
        allowParticipate: true,
        serverDate: 0,
        currentRoomDate: 0,
        progressTimer: null,
        serverDateTimer: null,
        socket: null,
        isLogin: !localStorage.getItem('token')
      }
    },
    computed: {
      loginstate() {
        return this.$store.state.status
      }
    },
    watch: {
      loginstate(newVal) {
        if (newVal === 'success') {
          this.getParticipateState()
          this.isLogin = false
        }
      }
    },
    methods: {
      initSocket() {
        this.socket = new WebSocket(`${wsUrl}/roll/${this.$store.state.currentRoolRoom.id}`)
        this.socket.onmessage = (res) => {
          if (res.data.length > 10) {
            this.serverDate = res.data
            this.currentRoomDate = res.data
            this.openProgress()
          }
        }
        this.socket.onerror = () => {
          // this.initSocket()
        }
      },
      initMqtt() {
        let ws = new WebSocket('ws://192.168.31.10:15674/ws')
        this.mqtt = Stomp.over(ws)
        this.mqtt.connect({
          login: 'admin',
          passcode: 'admin',
          host: 'room'
        }, () => {
          console.log(1223)
          this.mqtt.subscribe('roll', (res) => {
            console.log('收到消息', res)
          }, (error) => {
            console.log('错误消息', error)
          });
        }, (error) => {
          console.log(error)
        })
      },
      pagechange(currentPage){
        this.userPageNum = currentPage
        this.getUserList()
      },
      // 服务器时间进度
      serverDateprogress(){
        console.log(this.currentRoomDate, this.serverDate)
        if (this.serverDate < this.currentRoomDate) {//未到开奖时间
          this.serverDate += 300
          this.allowParticipate = false
          this.serverDateTimer = setInterval( () => {
            console.log('服务器时间进度')
            this.serverDate += 300
            if (this.serverDate >= this.currentRoomDate) {
              this.openProgress()
              console.log(this.$refs)
              clearInterval(this.serverDateTimer)
            }
          }, 300)
        } else if (this.serverDate - this.currentRoomDate >= 0 && this.serverDate - this.currentRoomDate <= 30 * 1000) {//开奖中
          this.openProgress()
        } else {//已开奖
          this.width = 101
        }
      },
      // 开奖进度
      openProgress() {
        // 初始进度
        this.allowParticipate = false
        this.width = Math.floor((this.serverDate - this.currentRoomDate) / (30 * 1000) * 100);
        console.log(this.width , 1)
        this.width ++
        this.progressTimer = setInterval(() => {
          if (this.width === 100) {this.$store.state.currentRoolRoom.status = 1}
          if (this.width > 100) {
            console.log(this.$refs.rollJackpots)
            // this.$refs.rollJackpots.reloadData()
            this.$store.commit('setCurrentRollRoom', { ... this.$store.state.currentRoolRoom, status: 1 })
            clearInterval(this.progressTimer)
          } else{
            this.width ++
          }
        }, 300)
      },
      participateIn(){
        if (localStorage.getItem('token')) {
          if (this.allowParticipate) {
            this.$api.post('/api/roll/into', {
              id: this.$store.state.currentRoolRoom.id
            }, res => {
              if (res.code === 200) {
                this.$confirm({
                  type: '提示',
                  time: '1',
                  msg: '参与成功',
                })
                if (this.userPageNum == 1) {
                  this.getUserList()
                }
                this.$store.state.currentRoolRoom.personNum
                this.allowParticipate = false
              } else {
                this.$confirm({
                  type: '提示',
                  time: '1',
                  msg: res.msg
                })
              }
            })
          }
        } else {
          Bus.$emit("get_login", event.target);
        }
      },
      getUserList() {
        this.$api.get('/api/roll/person/info', {
          id: this.$store.state.currentRoolRoom.id,
          pageNum: this.userPageNum,
          pageSize: 30
        }, res => {
          if (res.code === 200) {
            if (res.data) {
              this.list = res.data.content
            }
            this.userTotal = res.data.totalElements
          } else {
            this.$confirm({
              type: '提示',
              time: '1',
              msg: res.msg
            })
          }
        })
      },
      // 获取开奖状态
      getParticipateState() {
        this.$api.get('/api/roll/info', { id: this.$store.state.currentRoolRoom.id }, res => {
          if (res.code === 200) {
            this.allowParticipate = res.count === 0
          } else {
            this.allowParticipate = true
          }
        })
      },
      // 服务器时间
      getServerDate() {
        this.$api.get('/api/user/localTime', {}, res => {
          this.serverDate = res.data
          this.serverDateprogress()
        })
      },
      // 人满开开奖进度
      getOpenState() {
        this.$api.post('/api/roll/rollStartInfo', {id: this.$store.state.currentRoolRoom.id}, res => {
          if (res.code === 200) {
            if (res.data.lastJoinTime) {
              // this.currentRoomDate = new Date('2021-11-19 18:21:30').getTime()
              this.currentRoomDate = res.data.lastJoinTime
              this.$api.get('/api/user/localTime', {}, ress => {
                this.serverDate = ress.data
                if (this.serverDate - this.currentRoomDate < 30 * 1000 && this.serverDate - this.currentRoomDate >= 0) {
                  this.allowParticipate = false
                  this.openProgress()
                }
              })
            } else {
              this.initSocket()
            }
          }
        })
      }
    },
    created() {
      this.getUserList()
      this.getParticipateState()
      if (this.$store.state.currentRoolRoom.lotteryTime) {//按时间开奖初始化开奖时间
        this.getServerDate()
        this.currentRoomDate = new Date(this.$store.state.currentRoolRoom.lotteryTime).getTime()
      } else {//按人满开奖
        this.getOpenState()
      }
    },
    beforeDestroy() {
      clearInterval(this.serverDateTimer)
      clearInterval(this.progressTimer)
      if (this.socket) {
        this.socket.close()
      }
    }
  }
</script>

<style scoped>
  .gameHedar ul li p{
    font-size: 12px;
    color: #666666;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-top: 5px;
  }
  .gameHedar ul li div{
    width: 77px;
    height: 77px;
    border: 3px solid #4169A6;
    border-radius: 50%;
    overflow: hidden;
    margin:  0 auto;
    box-sizing: border-box;
  }
  .gameHedar ul li div img{
    width: 100%;
    height: 100%;
  }
  .gameHedar ul li{
    width: 94px;
    margin-right: 20px;
    margin-bottom: 25px;
  }
  .gameHedar ul li:nth-child(10n){
    margin-right: 0;
  }
  .gameHedar ul{
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }
  .gameHedar{
    padding: 30px 22px;
  }
  .Jackpot .settlement-box>div p{
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: #242C40;
  }
  .Jackpot .settlement-box>div{
     width: 360px;
     height: 8px;
     border-radius: 2px;
     overflow: hidden;
     background-image: url(../assets/roll-progress-bg.png);
     background-size: 100% 100%;
     margin:  20px auto;
     position: relative;
   }
  .Jackpot .settlement-box>p:first-child{
    font-size: 15px;
    font-weight: 400;
    color: #00ACE5;
    margin-top: 80px;
  }
  .Jackpot .settlement-box{
    width: 100%;
    height: 200px;
  }
  .RollRoom .amount-box{
    display: flex;
    padding-left: 15px;
    font-size: 16px;
    color: #999999;
    margin-top: 15px;
  }
  .RollRoom .amount-box>p{
    margin-right: 30px;
  }
  .RollRoom .amount-box>p:first-child span{
    color: #22A1AC;
    margin: 0 5px;
  }
  .RollRoom .amount-box>p:nth-child(2) span{
    color: #E59328;
    margin: 0 5px;
  }
  .modal-cent .title{
    width: 176px;
    height: 44px;
    background-image: url(../assets/roll-titlit-bg.png);
    background-size: 100% 100%;
    font-size: 26px;
    font-weight: 400;
    color: #FFFFFF;
    line-height: 44px;
    text-align: left;
    padding-left: 15px;
    box-sizing: border-box;
  }
  .modal-cent{
    margin-top: 50px;
    padding: 0 18px;
  }
  .hedar-box .text-box .activ{
     background-color: #59656E !important;
     color: #FFFFFF !important;
  }
  .hedar-box .text-box>div:last-child{
    font-size: 24px;
    font-weight: 400;
    width: 256px;
    height: 66px;
    line-height: 66px;
    background-color: #E59328;
    margin-right: 16px;
    cursor: pointer;
  }
  .hedar-box .text-box>div:first-child{
    font-size: 14px;
    color: #999999;
    text-align: left;
    padding-left: 28px;
  }
  .hedar-box .text-box>div:first-child p{
    margin-bottom: 10px;
  }
  .hedar-box .text-box>div:first-child p span{
    color: #22A1AC;
  }
  .hedar-box .text-box{
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-top: 12px;
  }
  .hedar-box .hedar-img-box>div{
    width: 76px;
    height: 76px;
    border: 2px solid #4169A6;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 15px;
  }
  .hedar-box .hedar-img-box>div img{
    width: 100%;
    height: 100%;
  }
  .hedar-box .hedar-img-box{
    display: flex;
    align-items: center;
    margin-top: 28px;
    margin-left: 28px;
    font-size: 18px;
    color: #FFFFFF;
    font-weight: 400;
  }
  .hedar-box .title{
    width: 286px;
    height: 48px;
    background-image: url(../assets/roll-titlit-bg.png);
    background-size: 100% 100%;
    line-height: 48px;
    color: #FFFFFF;
    font-size: 20px;
    text-align: left;
    padding-left: 20px;
    box-sizing: border-box;
  }
  .hedar-box{
    width: 1176px;
    margin: 0 auto;
    height: 250px;
    border: 1px solid #1D647C;
  }
  .RollRoom{
    background-color: #0E1421;
    width: 1200px;
    margin: 0 auto;
    padding-top: 36px;
    padding-bottom: 30px;
  }
</style>
